//
//  BaseTableViewController.m
//  MyShoes
//
//  Created by mac on 11-6-3.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BaseTableViewController.h"
#import "GlobalVar.h"
#import "Utitlity.h"
#import "RoomItemModel.h"

@interface BaseTableViewController ()
{

}

@end

@implementation BaseTableViewController
//@synthesize rows;
@synthesize showRefreshHeader;
@synthesize style;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    threadLoadData = YES;
    
    UIImageView *backimg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_middle"]];
    backimg.frame = self.view.bounds;
    [self.view addSubview:backimg];
    
	self.rows = [[NSMutableArray alloc]init];

	dataTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:style];
    dataTableView.backgroundColor= [UIColor clearColor];
    dataTableView.backgroundView = nil;
	dataTableView.dataSource = self;
	dataTableView.delegate = self;
    dataTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.view addSubview:dataTableView];
    
    dataTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 10)];

    nextPageCell =[[NextPageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PagenavigationCelldentifier"];
    /*
    if (_refreshHeaderView == nil && showRefreshHeader) {		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - dataTableView.bounds.size.height, self.view.frame.size.width, dataTableView.bounds.size.height)];
		view.delegate = self;
		[dataTableView addSubview:view];
		_refreshHeaderView = view;
		[view release];
        
        [_refreshHeaderView refreshLastUpdatedDate];
	}
    */
}

#pragma mark -
#pragma mark Overrwride

-(NSString *)refreshTag
{
    return @"BaseTableViewController";
}

-(CGFloat)rowHeight
{
    return 0;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(NSArray *)loadPageData:(int)page
{
    return nil;
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	_reloading = YES;
    _page =1;
	isLoadingNextPage= NO;
    if (threadLoadData) {
        [NSThread detachNewThreadSelector:@selector(loadDataThread) toTarget:self withObject:nil];
    }else{
        [self loadPageData:_page];
    }
}


-(void)startLoadNextPage
{
	isLoadingNextPage = YES;
	[nextPageCell start];
    _page++;
	if (threadLoadData) {
        [NSThread detachNewThreadSelector:@selector(loadDataThread) toTarget:self withObject:nil];
    }else{
        [self loadPageData:_page];
    }
}

-(void)loadDataThread
{
	//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSArray *theresult = [self loadPageData:_page];
	[self performSelectorOnMainThread:@selector(doneLoadingTableViewData:) withObject:theresult waitUntilDone:YES];
	//[pool release];
}

- (void)doneLoadingTableViewData:(NSArray *)theresult{
    
    if (isLoadingNextPage) {
        isLoadingNextPage = NO;
        [nextPageCell over];
        if (theresult && [theresult count]>0) {
            [self.rows addObjectsFromArray:theresult];
        }else {
            haveNextPage = NO;
        }
    }else{
        NSLog(@"removeralllllllll");
        [self.rows removeAllObjects];
        if (theresult && [theresult count]>0) {
            [self.rows addObjectsFromArray:theresult];
            haveNextPage = YES;
        }else {
            haveNextPage = NO;
        }
        _reloading = NO;
        if (showRefreshHeader) {
            
            //[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:dataTableView];
        }
    }

    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *datestr=[date stringFromDate:[NSDate date]];
    [GlobalVar saveData:datestr forKey:[self refreshTag]];

    [dataTableView reloadData];
    
}


-(void)refreshData{
    if (showRefreshHeader) {
        [dataTableView setContentOffset:CGPointMake(0, -65.0f) animated:NO ];	
        //[_refreshHeaderView egoRefreshScrollViewDidEndDragging:dataTableView];
    }else{
        [self reloadTableViewDataSource];
    }
}

/*
#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{	
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    NSString *datestr = [GlobalVar getDataForKey:[self refreshTag]];
    NSDate *d = nil;
    if (datestr) {
        NSDateFormatter *date=[[[NSDateFormatter alloc] init]autorelease];
        [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        d=[date dateFromString:datestr];
    }
	return d; 
}
*/


#pragma mark -
#pragma mark UITableViewDataSource


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	NSUInteger row = [indexPath row];
	if (row < rownum) {
        return [self rowHeight];
	}else {
		return 40;
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (self.rows && [self.rows count]>0){
        rownum = [self.rows count];
		if (haveNextPage && !closeNextPage) {
			return rownum+1;
		}else {
			return rownum;
		}
	}else {
		return 0;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	if (row < rownum) {
        return [self cellForRowAtIndexPath:indexPath];
	}else {
		return nextPageCell;
	}
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	NSUInteger row = [indexPath row];
	if (row < rownum) {
        [self didSelectRowAtIndexPath:indexPath];
    }else {
		if (isLoadingNextPage) {
			return;
		}		
		[self startLoadNextPage];
	}
}

- (void)canLoadNextPage {
	if (isLoadingNextPage || !haveNextPage || closeNextPage) {
		return;
	}
    [self startLoadNextPage];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (showRefreshHeader) {
        //[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
	if ((scrollView.contentOffset.y>0) &&( scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height + 10) ) {
		[self canLoadNextPage];
	}

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
    if (showRefreshHeader) {
        //[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
}

#pragma mark - RoomList
- (void)requestGetRoomList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_list",ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                NSMutableArray *list = [NSMutableArray arrayWithCapacity:10];
                NSArray *devList = retJsonData[@"data"];
                for (NSDictionary *item in devList) {
                    
                    RoomItemModel *data = [[RoomItemModel alloc] initWithJSON:item];
                    [list addObject:data];
                }
                _roomDataList = list;
            }
            NSLog(@"resultItem:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
        
    }
}


         
@end
